package com.fjzx.androidframe.network;

import android.arch.lifecycle.MediatorLiveData;

import com.fjzx.androidframe.global.entity.Resource;

/**
 * 基础LiveData，封装了请求状态
 *
 * @author xiongyongcong
 */
public class BaseLiveData<T> extends MediatorLiveData<Resource<T>> {
    private Resource<T> resource;

    public BaseLiveData(String action) {
        this.resource = new Resource<>(action);
    }

    public BaseLiveData(String action, int loadingMsgId) {
        this.resource = new Resource<>(action);
        loading(loadingMsgId);
    }

    public BaseLiveData(Resource<T> resource) {
        this.resource = resource;
        loading();
    }

    /**
     * 设置加载中状态
     */
    public BaseLiveData loading() {
        this.resource.loading();
        postValue(this.resource);
        return this;
    }

    public BaseLiveData loading(int msgId) {
        this.resource.loading(msgId);
        postValue(this.resource);
        return this;
    }

    /**
     * 设置成功状态
     *
     * @param data
     */
    public BaseLiveData success(T data) {
        this.resource.success(data);
        postValue(this.resource);
        return this;
    }

    /**
     * 设置失败状态
     *
     * @param msg
     */
    public BaseLiveData error(String msg) {
        this.resource.error(msg);
        postValue(this.resource);
        return this;
    }

    public Resource<T> getResource() {
        return resource;
    }
}
